package calculation.application;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

import calculation.base.*;

/**
 * 
 * @author Zhu Leyao,Chen Yongbing
 * @version 1.0.1
 */
public class StudentGPACalculation {
	
	private static BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
	private Student student;
	public static void main(String[] args) throws IOException {
		
		StudentGPACalculation calculation1 = new StudentGPACalculation();
		
		calculation1.run();
	}
	
	private void run() throws IOException {
		student = new Student();
		int choice = getChoice();
		while(choice != 0) {
			if(choice == 1) {
				student.addSubject(readSubject());
			}
			else if(choice == 2) {
				student.removeSubject(readSubject());
			}
			else if(choice == 3) {
				System.out.println(student.toString());
			}
			else if(choice == 4) {
				System.out.print("Your GPA is ");
				System.out.printf("%.2f",student.getGPA());
				System.out.println();
			}
			choice = getChoice();
		}
	}
	
	private int getChoice() throws IOException {
		//用于接收用户输入的选项
		int number;
		
		
		while(true) {
			
			try {
				System.out.println("[0] Quit\n"+
								   "[1] Add Score\n"+
								   "[2] Remove Score\n"+
								   "[3] Display All Scores\n"+
								   "[4] Calculate GPA\n"+
								   "Please input your choice: ");
				number = Integer.parseInt(stdIn.readLine());
				
				if(number>=0&&number<=4) {
					return number;
				}
				else {
					System.out.println("\nInvalid input!! Please try again: ");
				}
				
			} catch (NumberFormatException e) {
				System.out.print(e);
			}
		}
	}
	
	public Subject readSubject() throws IOException {
		final String DELIM = "_";
		String subject = null;
		int credit;
		double score;
		while(true) {
			System.out.println("Please input your score [subject_credit_score] :");
		
			StringTokenizer tokenizer = new StringTokenizer(stdIn.readLine(), DELIM);

			if (tokenizer.countTokens() != 3) {
				System.out.println("\nInvalid input!! Please try again: ");
			} else {
				subject = tokenizer.nextToken();
				try {
					credit = Integer.parseInt(tokenizer.nextToken());
					score = Double.parseDouble(tokenizer.nextToken());
				
					if(credit < 0||score < 0 ||score >100) {
						System.out.println("\nInvalid input!! Please try again: ");
					}
					else {
						break;
					}
				} catch (NumberFormatException e) {
					System.out.println(e);
				}
			}
		}
		return new Subject(subject,credit,score);
	}
	
//	public Subject readSubjectRemove() {
//		
//	}
}
